#!/usr/bin/env bash

set -x
set -e
set -f
set -u

branch="$1"
case "$branch" in
	rosa2021.1 | rosa2019.05 | rosa2016.1 ) : ;;
	* ) exit 1 ;;
esac

repo="$2"
case "$repo" in
	main | contrib | non-free ) : ;;
	* ) exit 1 ;;
esac

spec="$3"
test -f "$spec"
dir="$(dirname "$spec")"

commit_msg="${commit_msg:-Init}"

_rpmspec(){
	rpmspec --define "_sourcedir $dir" "$@"
}

srpm_name="$(_rpmspec -q --srpm --qf '%{name}' "$spec")"
test -n "$srpm_name"

srpm_summary="$(_rpmspec -q --srpm --qf '%{summary}' "$spec")"
test -n "$srpm_summary"

srpm_description="$(_rpmspec -q --srpm --qf '%{description}' "$spec")"
test -n "$srpm_description"

project_description="$srpm_summary

$srpm_description"

abf create_empty --description "$project_description" --visibility public "$srpm_name" import

pushd "$dir"
git init
git remote add origin git@abf.io:import/"$srpm_name".git

# XXX spectool -g *.spec fails for some reasons
if grep -q '^%generate_buildrequires' "$spec"
then
	source0="$(_rpmspec -P "$spec" | grep ^Source0 | awk '{print $NF}')"
	test -n "$source0"
	rm -fv "$(basename "$source0")"
	wget "$source0"
	unset source0
else
	spectool --define "_sourcedir $dir" -g "$spec"
fi
abf put
git add .
git commit -m "$commit_msg"
git push --set-upstream origin master
git checkout -b "$branch"
git push --set-upstream origin "$branch"
#git push --all
popd

abf add -p import/"$srpm_name" "$branch"/"$repo"
abf build -b "$branch" --testing --auto-publish-status testing -p import/"$srpm_name"
